package uit.mmt02.activity;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import uit.mmt02.R;
import uit.mmt02.mailControl.MdeamonControl;
import uit.mmt02.share.ConvertMessageToList;
import uit.mmt02.share.OneMail;
import uit.mmt02.share.myadapter;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class getNoiboActivity extends ListActivity
{
	final static String KEY_USERNAME_LOGIN = "USERNAMELOGIN"; // nhan USERVA PASS tu showmail activity gui toi de login
	final static String KEY_PASSWORD_LOGIN = "PASSWORDLOGIN";
	ArrayAdapter<OneMail>adapter;
	List<OneMail>list;
	String username  ;
	String password  ;
	MdeamonControl mdaemon;
	Bundle bundle;
	String tag = "getNoiBoA";

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		list = new ArrayList<OneMail>();
		bundle = getIntent().getExtras(); // nhan usrename va pass gui toi
		username = bundle.getString(KEY_USERNAME_LOGIN);
		password = bundle.getString(KEY_PASSWORD_LOGIN);
		Log.v(tag, "Nhan duoc : " + username + " | " + password);
		new loadMailNoibo().execute("mdaemon");
		
	}
	
	private class loadMailNoibo extends AsyncTask<String, String, List<OneMail>>
	{
		ProgressDialog pd = new ProgressDialog(getNoiboActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
//			pd.setTitle("Lay Mail Noi Bo");
			pd.setMessage("Dang tai mail tu server...");
			pd.show();
			super.onPreExecute();
		}
		
		@Override
		protected List<OneMail> doInBackground(String... params) {
			// TODO Auto-generated method stub
//			mdaemon = new MailNoiBoControl("192.168.1.2", "u2", "123456", 110);
//			list =  mdaemon.getMailNoiBo();
			mdaemon = new MdeamonControl(username, password);
			Message[]mess = mdaemon.getmail2();
			ConvertMessageToList cv = new ConvertMessageToList();
			list = cv.convert2(mess);
			if(list.size() ==0)
			{
				list.add(new OneMail());
				list.add(new OneMail());
			}
			
			adapter = new myadapter(getNoiboActivity.this, list);
			return list;
		}
		 @Override
		protected void onPostExecute(List<OneMail> result) {
			// TODO Auto-generated method stub
//			 ListView lv = getListView();
//			 LayoutInflater inflater = getLayoutInflater();
//			 View view = inflater.inflate(R.layout.footer_list_mail, null);
//			 lv.addFooterView(view);
			 setListAdapter(adapter);
			 pd.dismiss();
			super.onPostExecute(result);
		}
	}
}
